import React from 'react';
import { Button } from 'antd';
import AudioRecorder from '@/utils/recorder';
import { fixDuration } from '@/utils/recorder/lib';
import { clipAudio } from '@/utils/recorder/clip';
import useUploadOss from '@/hooks/useUploadOss';

let timer;
const {
    recInitialize,
    recStart,
    recStop,
    recPlay,
    getBlob,
    // getSliceUrl,
    getRecDuration,
    destroy
} = new AudioRecorder();

export default function Recorder() {
    const [uploadFile] = useUploadOss();
    const ref = React.useRef();
    const clipRef = React.useRef();

    const handleStart = () => {
        recStart();
        timer = setInterval(() => {
            console.log(getRecDuration());
        }, 1000);
    };

    const handleStop = () => {
        recStop();
        clearInterval(timer);
    };

    const handleUpload = async () => {
        const blob = getBlob();
        const file = new window.File([blob], `${+new Date()}.mp3`, { type: blob.type });
        const result = await uploadFile(file);
        console.log(result, '===上传成功===');
    };

    const handlePlay = () => {
        recPlay();
    };

    const handleClip = () => {
        // 只播放片段
        // clipRef.current.src = getSliceUrl(ref.current.src, [1, 2]); // seconds

        // 实际剪切片段，没那么精准
        clipAudio(ref.current.src, [0, 4], result => {
            fixDuration(clipRef.current);
            clipRef.current.src = result;
        });
    };

    React.useEffect(() => {
        recInitialize();

        return () => {
            destroy();
            if (timer) clearInterval(timer);
        };
    }, []);

    return (
        <div style={{ display: 'flex', flexDirection: 'column', width: 300 }}>
            <Button onClick={handleStart}>开始录音</Button>
            <Button onClick={handleStop}>结束录音</Button>
            <Button onClick={handleUpload}>上传录音</Button>
            <Button onClick={handlePlay}>播放录音</Button>
            <Button onClick={handleClip}>切割录音</Button>
            <audio ref={ref}>
                <track kind="captions" />
                您的浏览器不支持 audio 标签。
            </audio>
            <div>
                <div className="audio-duration"></div>
                <div style={{ height: 30 }} className="audio-wave"></div>
            </div>
            <audio controls="controls" ref={clipRef}>
                <track kind="captions" />
                您的浏览器不支持 audio 标签。
            </audio>
        </div>
    );
}
